package com.aoxon.cargo.activity.n;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.BaseActivity;
import com.aoxon.cargo.activity.CargoActivity;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.component.n.CargoItemizedOverlay;
import com.aoxon.cargo.service.HotSupplierService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.shared.LocationShared;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.BMapUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class PurMapActivity extends BaseActivity {

	private BMapManager mBMapMan = null;
	private MapView mMapView = null;
	private Context context;
	private MapController mMapController;
	private GeoPoint myloc_point;
	private GeoPoint suploc_point;
	private LocationClient mLocationClient;
	private ImageView locate;

	public static List<Supplier> suppliers = null;
	public static Supplier supplier = null;

	// 加载模式
	public static short LAUNCH_MODE = 0;
	public static final short ONLY_MY_LOC = 0;
	public static final short MY_LOC_AND_SUP = 1;
	public static final short MY_LOC_AND_SUPLIST = 2;

	private final int ANIMATE_TO_SUP = 2;
	private final int ADDSUPS = 3;

	private boolean isStart = false;
	private boolean initPop = false;
	private boolean requestLoc = true;
	private boolean getCloseSups = false;

	private MyLocationOverlayWithPop mLocOverlay;
	private LocationData mLocData;
	private BDLocation bdLocation;
	private LinearLayout popView;
	private PopupOverlay mPopupOverlay;
	private TextView accuracy_tv;
	private TextView my_loc_msg;
	private CargoItemizedOverlay cOverlay = null;
	private View close_sup_layout;

	private HotSupplierService closeSupplierService = (HotSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.HOT_SUPPLIER);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		mBMapMan = new BMapManager(this.getApplicationContext());
		mBMapMan.init(null);
		// 注意：请在试用setContentView前初始化BMapManager对象，否则会报错

		setContentView(R.layout.pur_map_n);
		locate = (ImageView) findViewById(R.id.locate);
		locate.setOnClickListener(clickToMyLoc);
		mMapView = (MapView) findViewById(R.id.bmapsView);
		mMapController = mMapView.getController();
		myloc_point = LocationShared.getLastLocation();
		if (myloc_point != null) {
			mMapController.setCenter(myloc_point);
			mMapView.refresh();
			Log.v("GeoPoint", DataUtil.gson.toJson(myloc_point));
		}
		// 定位配置信息
		LocationClientOption locationOption = new LocationClientOption();
		locationOption.setOpenGps(true);
		locationOption.setCoorType("bd09ll");
		locationOption
				.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		locationOption.setAddrType("all");
		locationOption.setProdName("BaiduLocation");
		locationOption.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		locationOption.disableCache(true);// 禁止启用缓存定位
		// locationOption.setPoiNumber(5); // 最多返回POI个数
		// locationOption.setPoiDistance(1000); // poi查询距离
		locationOption.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息

		mPopupOverlay = new PopupOverlay(mMapView, new PopupClickListener() {

			@Override
			public void onClickedPopup(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		mLocationClient = new LocationClient(context, locationOption);
		popView = (LinearLayout) findViewById(R.id.my_msg);
		mLocData = new LocationData();
		mLocOverlay = new MyLocationOverlayWithPop(mMapView);
		mLocOverlay.enableCompass();
		mMapView.getOverlays().add(mLocOverlay);
		mMapView.setOnClickListener(mapOnclick);
		mLocationClient.registerLocationListener(new MyLocationListener());

	}

	private Thread getSupsThread = new Thread(new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			GsonBean gsonBean = null;
			gsonBean = closeSupplierService.execute(0, 15);
			try {
				if (CheckStateUtil.check(gsonBean)) {
					suppliers = DataUtil.gson.fromJson(gsonBean.getStrJson(),
							new TypeToken<List<Supplier>>() {
							}.getType());
					handler.sendEmptyMessage(ADDSUPS);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	});

	private Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == ANIMATE_TO_SUP) {
				mMapController.animateTo(suploc_point);
			} else if (msg.what == ADDSUPS) {
				cOverlay.setItems(suppliers);
				mMapView.refresh();
			}
			super.dispatchMessage(msg);
		}
	};

	private void init() {
		if (LAUNCH_MODE == ONLY_MY_LOC) {
			mMapController.setZoom(18);
		} else {
			cOverlay = new CargoItemizedOverlay(mMapView, mPopupOverlay);
			if (LAUNCH_MODE == MY_LOC_AND_SUPLIST) {
				if (suppliers == null) {
					ToastUtil.show(PurMapActivity.this, "数据获取中..");
					getCloseSups = true;
				} else
					cOverlay.setItems(suppliers);
			} else {

				requestLoc = false;
				// 定位到单个商家
				cOverlay.setItem(supplier);
				suploc_point = cOverlay.getItem(0).getPoint();

				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(200);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						handler.sendEmptyMessage(ANIMATE_TO_SUP);
						Log.v("handler", "177");

					}
				}).start();
			}
			mMapController.setZoom(16);
			mMapView.getOverlays().add(cOverlay);
			mMapView.refresh();
		}
	}

	OnClickListener mapOnclick = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			popView.setVisibility(View.GONE);
		}
	};

	// 点击定位到 我的位置
	OnClickListener clickToMyLoc = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (requestLoc) {
				ToastUtil.show(PurMapActivity.this, "正在定位...");
			} else {
				if (LAUNCH_MODE == MY_LOC_AND_SUPLIST)
					mMapController.setZoom(16);
				else
					mMapController.setZoom(18);
				mMapController.animateTo(myloc_point);
				mMapView.refresh();
			}
		}
	};

	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			bdLocation = location;
			if (location.getLocType() == 167) {
				ToastUtil.show(getBaseContext(), "定位失败，请耐心等待");
				return;
			}
			mLocData.latitude = location.getLatitude();
			mLocData.longitude = location.getLongitude();
			mLocData.accuracy = location.getRadius();
			mLocData.direction = location.getDerect();
			mLocOverlay.setData(mLocData);
			if (myloc_point == null)
				myloc_point = new GeoPoint(
						(int) (bdLocation.getLatitude() * 1E6),
						(int) (bdLocation.getLongitude() * 1E6));
			else {
				myloc_point
						.setLatitudeE6((int) (bdLocation.getLatitude() * 1E6));
				myloc_point
						.setLongitudeE6((int) (bdLocation.getLongitude() * 1E6));
			}
			if (requestLoc && LAUNCH_MODE != MY_LOC_AND_SUP) {
				requestLoc = false;
				if (LAUNCH_MODE == MY_LOC_AND_SUPLIST)
					mMapController.setZoom(16);
				else
					mMapController.setZoom(18);
				mLocOverlay.callDistpatchTap();
				mMapController.animateTo(myloc_point);
				Log.v("myloc_point", new Gson().toJson(myloc_point));
			}

			if (getCloseSups && suppliers == null) {
				getSupsThread.start();
				getCloseSups = false;
			}
			mMapView.refresh();
		}

		@Override
		public void onReceivePoi(BDLocation location) {
			// TODO Auto-generated method stub

		}
	}

	class MyLocationOverlayWithPop extends MyLocationOverlay {

		public MyLocationOverlayWithPop(MapView view) {
			super(view);
		}

		public void callDistpatchTap() {
			dispatchTap();
		}

		@Override
		protected boolean dispatchTap() {
			// TODO Auto-generated method stub
			if (!initPop) {
				accuracy_tv = (TextView) findViewById(R.id.accuracy);
				my_loc_msg = (TextView) findViewById(R.id.mylocmsg);
				close_sup_layout = findViewById(R.id.close_sup);
			}
			close_sup_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					popView.setVisibility(View.GONE);
					Bundle data = new Bundle();
					data.putString("ClosePoint", DataUtil.gson.toJson(BMapUtil
							.getAround(mLocData, 1000)));
					Intent intent = new Intent(context,
							PurSupplierCloseActivity.class);
					intent.putExtras(data);
					startActivity(intent);

				}
			});
			accuracy_tv.setText("(精确度"
					+ String.valueOf((int) mLocData.accuracy) + "米）");
			my_loc_msg.setText(bdLocation.getAddrStr());
			popView.setVisibility(View.VISIBLE);
			initPop = true;

			return super.dispatchTap();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (LAUNCH_MODE == MY_LOC_AND_SUPLIST)
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_INDEX;
			else
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_MORE;
			Intent intent = new Intent(getBaseContext(), CargoActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	@Override
	protected void onDestroy() {

		Log.v("PurMapAcitivity", "OnDestory");
		mMapView.destroy();
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		if (mLocationClient != null) {
			mLocationClient.stop();
			isStart = false;
		}
		if (cOverlay != null) {
			cOverlay.removeAll();
			cOverlay = null;
		}
		if (suppliers != null) {
			suppliers.clear();
			suppliers = null;
		}
		if (supplier != null) {
			supplier = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {

		Log.v("PurMapAcitivity", "OnPause");
		mMapView.onPause();
		if (mBMapMan != null) {
			mBMapMan.stop();
		}
		if (isStart) {
			mLocationClient.stop();
			isStart = false;
		}
		LocationShared.saveLostLocatioin(myloc_point);

		Log.v("Destroy_GeoPoint", DataUtil.gson.toJson(myloc_point));
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.v("PurMapAcitivity", "OnResume");
		mMapView.onResume();
		if (mBMapMan != null) {
			mBMapMan.start();
		}
		if (!isStart) {
			mLocationClient.start();
			isStart = true;
		}

		super.onResume();
		mMapView.refresh();
		Log.v("LaunchMode", String.valueOf(LAUNCH_MODE));
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		init();
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		if (cOverlay != null) {
			cOverlay.removeAll();
			cOverlay = null;
		}
		if (mPopupOverlay != null) {
			mPopupOverlay.hidePop();
		}
		super.onStop();
	}
}
